<script setup lang="ts">
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { DepartmentApi } from '#/api/system/department';

import { nextTick, onMounted, watch } from 'vue';

import { ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteDepartment, getDepartmentList } from '#/api/system/department';
import { EditInfo } from '#/components/edit-info/index';
import { $t } from '#/locales';
import { useDepartmentGridColumns } from '#/views/system/company/data';

interface Props {
  companyId: number;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  deleteDepartment: [row: DepartmentApi.Department];
  editDepartment: [row: DepartmentApi.Department];
}>();

/** 删除部门 */
async function onDepartmentDelete(row: DepartmentApi.Department) {
  await ElMessageBox.confirm('确定要删除该部门吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  await deleteDepartment(row.id as number);
  ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
  // 刷新当前部门列表
  departmentGridApi.query();
  // 通知父组件
  emit('deleteDepartment', row);
}

function onDepartmentEdit(row: DepartmentApi.Department) {
  emit('editDepartment', row);
}

function onDepartmentActionClick({
  code,
  row,
}: OnActionClickParams<DepartmentApi.Department>) {
  switch (code) {
    case 'delete': {
      onDepartmentDelete(row);
      break;
    }
    case 'edit': {
      onDepartmentEdit(row);
      break;
    }
  }
}

const [DepartmentGrid, departmentGridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useDepartmentGridColumns(onDepartmentActionClick),
    height: 300,
    proxyConfig: {
      autoLoad: false, // 禁用自动加载，手动控制查询时机
      ajax: {
        query: async () => {
          const result = await getDepartmentList({
            companyId: props.companyId,
          });
          return result.list || [];
        },
      },
    },
    pagerConfig: {
      enabled: false,
    },
  } as VxeTableGridOptions<DepartmentApi.Department>,
});

// 组件挂载后触发初始查询
onMounted(async () => {
  await nextTick();
  if (departmentGridApi.grid) {
    departmentGridApi.query();
  }
});

// 监听 companyId 变化，重新查询数据
watch(
  () => props.companyId,
  (newCompanyId, oldCompanyId) => {
    // 只有当 companyId 真正改变时才查询
    if (newCompanyId !== oldCompanyId && departmentGridApi.grid) {
      departmentGridApi.query();
    }
  },
  { immediate: false },
);

// 暴露刷新方法给父组件
defineExpose({
  refresh: () => {
    if (departmentGridApi.grid) {
      departmentGridApi.query();
    }
  },
});
</script>

<template>
  <DepartmentGrid>
    <template #edit-info="{ row }">
      <EditInfo :handler-name="row.handlerName" :time="row.updateTime" />
    </template>
  </DepartmentGrid>
</template>
